﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using customer.dao.V2;
using Nancy;
using Nancy.ModelBinding;


namespace customer.dao
{
    public class SchemaModule : NancyModule
    {
        
        SchemaReaderBuilder _schemaReaderBuilder = null;

        public SchemaModule(SchemaReaderBuilder schemaReaderBuilder)
        {
            _schemaReaderBuilder = schemaReaderBuilder;

            this.Post("/schema", x => SchemaTotal(x));
            this.Post("/schema/{collectionName}", x => SchemaCollectionName(x));

            this.Post("/schema/{collectionName}/{tableName}", x => SchemaRestrictions_tableName(x));
            this.Post("/schema/{collectionName}/{tableName}/{columnName}", x => SchemaRestrictions_columnName(x));
        }

        dynamic SchemaTotal(dynamic x)
        {
            var sm = this.Bind<SchemaLookupModel>();

            var result = _schemaReaderBuilder.GetSR(sm.DB).GetSchema();

            return this.Response.AsText(result.ToString(), "application/json");
        }

        dynamic SchemaCollectionName(dynamic x)
        {
            var sm = this.Bind<SchemaLookupModel>();
            string collectionName = x.collectionName;

            var result = _schemaReaderBuilder.GetSR(sm.DB).GetSchema(collectionName);

            var json = result.ToString();
            return this.Response.AsText(json, "application/json");
        }

        dynamic SchemaRestrictions_tableName(dynamic x)
        {
            var sm = this.Bind<SchemaLookupModel>();
            string collectionName = x.collectionName;
            string tableName = x.tableName;

            string[] restrictionValues = new string[4];
            restrictionValues[0] = null; // Catalog
            restrictionValues[1] = null; // Owner
            restrictionValues[2] = tableName; // Table
            restrictionValues[3] = null; // Column

            var result = _schemaReaderBuilder.GetSR(sm.DB).GetSchema(collectionName, restrictionValues);

            return this.Response.AsText(result.ToString(), "application/json");
        }

        dynamic SchemaRestrictions_columnName(dynamic x)
        {
            var sm = this.Bind<SchemaLookupModel>();
            string collectionName = x.collectionName;
            string tableName = x.tableName;
            string columnName = x.columnName;

            string[] restrictionValues = new string[4];
            restrictionValues[0] = null; // Catalog
            restrictionValues[1] = null; // Owner
            restrictionValues[2] = tableName; // Table
            restrictionValues[3] = columnName; // Column

            var result = _schemaReaderBuilder.GetSR(sm.DB).GetSchema(collectionName, restrictionValues);

            return this.Response.AsText(result.ToString(), "application/json");
        }

    }
}
